import MusicManager from "../../../MusicManager";
import HealthPoint, { Killer } from "../../funcObj/interface/HealthPoint";
import GameManager from "../../manager/GameManager";
import Player from "../../player/Player";
import DefensiveFacility from "../DefensiveFacility";

const { ccclass, property } = cc._decorator;

/**
 * 镭射炮
 */
@ccclass
export default class LaserGun extends DefensiveFacility {

    @property(cc.Node)
    Line: cc.Node = null;

    @property(cc.Node)
    light: cc.Node = null;

    @property(cc.Node)
    dark: cc.Node = null;

    @property(cc.Animation)
    anima: cc.Animation = null;

    time = 0;

    audioId: number;

    init(player: Player): void {
        super.init(player);
        this.time = 0;
        this.Line.getComponent(cc.Animation).stop();
        this.dark.active = false;

        let laserParent = GameManager.instance.laserParent;
        this.Line.position = laserParent.convertToNodeSpaceAR(this.Line.convertToWorldSpaceAR(cc.Vec3.ZERO));
        this.Line.parent = laserParent;
        this.Line.setSiblingIndex(999);
    }

    protected update(dt: number): void {
        let target = this.getClosestTarget();
        if (target) {
            this.shot(target);
            this.time += dt;
            if (this.time > this.facilityInfo.攻击间隔) {
                this.time = 0;
                target.reducedHp({ player: this.player, facility: this, domage: this.facilityInfo.攻击力 })
            }
        } else {
            this.Line.active = false;
            this.dark.active = false;
            this.anima.stop();
            this.Line.getComponent(cc.Animation).stop();
        }
    }

    shot(target: HealthPoint) {
        //将炮口对准怪物
        this.Line.active = true;
        let targetPosition = target.node.position;
        let direction = cc.v2(targetPosition.x - this.Line.position.x, targetPosition.y - this.Line.position.y);
        let angle = cc.misc.radiansToDegrees(cc.Vec2.angle(direction, cc.v2(0, 1)));
        this.Line.angle = direction.x > 0 ? 360 - angle : angle;
        this.light.height = direction.mag();
        if (!this.anima.getAnimationState("run").isPlaying) {
            this.anima.play();
            this.Line.getComponent(cc.Animation).play();
            MusicManager.instance.play(MusicManager.instance.laser, this.Line, true);
        }
    }

    die(killer: Killer): void {
        this.Line.parent = this.node;
        this.Line.active = false;
        this.dark.active = false;
        this.Line.getComponent(cc.Animation).stop();
        this.anima.stop();
        this.Line.position = cc.v3(0, 50);
        super.die(killer);
    }
}
